//
//  JSONCoder+Extension.swift
//  MKCodable
//
//  Created by 苏尚进 on 2020/5/21.
//  Copyright © 2020 moon. All rights reserved.
//

import Foundation

extension Codable {
    @inlinable public var mkcodable:NameSpace<Self>{
        get { return NameSpace<Self>(self) }
        set { self = newValue.value }
    }
    @inlinable public static var mkcodable:NameSpace<Self>.Type { return NameSpace<Self>.self }
}

extension NameSpace where T:Codable {
    /// 编码为json格式的数据
    ///
    /// - Returns: json格式数据,类型如下:NSArray,NSDictaionry,NSNumber,NSNull,NSString
    /// - Throws: CodingError中相应的错误
    public func encodeToJSON(_ outputFormatting: JSONSerialization.WritingOptions = []) -> NSObject? {
        let jsonCoder = JSONCoder()
        jsonCoder.outputFormatting = outputFormatting
        let jsonData:NSObject? = jsonCoder.encode(self.value)
        return jsonData
    }
    public func encodeToJSONString(_ outputFormatting: JSONSerialization.WritingOptions = []) -> String? {
        let jsonCoder = JSONCoder()
        jsonCoder.outputFormatting = outputFormatting
        let jsonData:String? = jsonCoder.encode(self.value)
        return jsonData
    }
    public func encodeToJSONData(_ outputFormatting: JSONSerialization.WritingOptions = []) -> Data? {
        let jsonCoder = JSONCoder()
        jsonCoder.outputFormatting = outputFormatting
        let jsonData:Data? = jsonCoder.encode(self.value)
        return jsonData
    }
    /// 解码json数据,然后更新对象
    ///
    /// - Parameter data: json格式的数据,支持以下类型:json格式的字符串,json格式的字符串Data,[Any],[String:Any],NSNumber,NSNull
    /// - Throws: CodingError中相应的错误
    public mutating func decodeFromJSON(_ data:Any) {
        let jsonCoder = JSONCoder()
        jsonCoder.decode(&self.value, from: data)
    }
    
    /// 解码json数据,然后更新对象
    ///
    /// - Parameter data: json格式的数据,支持以下类型:json格式的字符串,json格式的字符串Data,[Any],[String:Any],NSNumber,NSNull
    /// - Returns: 解码出来的对象
    /// - Throws: CodingError中相应的错误
    public static func decodeFromJSON(_ data:Any) -> T? {
        let jsonCoder = JSONCoder()
        return jsonCoder.decode(T.self, from: data)
    }
}
